package com.bootdo.wx.service.impl;

import com.bootdo.common.config.Constant;
import com.bootdo.common.utils.*;
import com.bootdo.common.utils.excel.OrderExcelUtils;
import com.bootdo.system.dao.UserDao;
import com.bootdo.wx.api.ApiWeChatPayController;
import com.bootdo.wx.dao.*;
import com.bootdo.wx.domain.*;
import com.bootdo.wx.service.MemberUpgradeService;
import com.bootdo.wx.service.WeChatPayService;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.n3r.idworker.Id;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import com.bootdo.wx.service.OrderOrderService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;

import static com.bootdo.common.utils.ShiroUtils.getUserId;

@Service
public class OrderOrderServiceImpl implements OrderOrderService {
	@Autowired
	private OrderOrderDao orderOrderDao;
	@Autowired
	private OrderShippingDao orderShippingDao;
	@Autowired
	private MemberUserDao memberUserDao;
	@Autowired
	private MemberAddressDao memberAddressDao;
	@Autowired
	private GoodsProductDao goodsProductDao;
	@Autowired
	private OrderDetailDao orderDetailDao;
	@Autowired
	private CmsContentDao cmsContentDao;
	@Autowired
	private OrderComDao orderComDao;
	@Autowired
	private MemberCartDao memberCartDao;
	@Autowired
	private GoodsGoodsDao goodsGoodsDao;
	@Autowired
	private OrderComentDao orderComentDao;
	@Autowired
	private MemberCouponDao memberCouponDao;
	@Autowired
	private GoodsSpikeDao goodsSpikeDao;
	/*
	 * @Autowired private GoodsNineDao goodsNineDao;
	 */
	@Autowired
	private GoodsBargainDao goodsBargainDao;
	@Autowired
	private OrderBargainDao orderBargainDao;
	@Autowired
	private OrderBargainUserDao orderBargainUserDao;
	@Autowired
	private ShopExpressMessageDao shopExpressMessageDao;
	@Autowired
	private ShopExpressCodeDao shopExpressCodeDao;
	@Autowired
	private ShopExpressDetailsDao shopExpressDetailsDao;
	@Autowired
	private OrderExcelRecodeDao orderExcelRecodeDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private OrderBackDao orderBackDao;
	@Autowired
	private MemberPriceDao memberPriceDao;
	@Autowired
	private MemberScoreDao memberScoreDao;
	/*
	 * @Autowired private SetWechatDao setWechatDao;
	 */
	@Autowired
	private GoodsTeamDao goodsTeamDao;
	@Autowired
	private OrderTeamDao orderTeamDao;
	@Autowired
	private OrderTeamUserDao orderTeamUserDao;
	@Autowired
	private GoodsUpgradeDao goodsUpgradeDao;
	/*
	 * @Autowired private MemberUpgradeService memberUpgradeService;
	 * 
	 * @Autowired private MemberLevelChangeDao memberLevelChangeDao;
	 */
	@Autowired
	private WeChatPayService weChatPayService;
	@Autowired
	private OrderSetDao orderSetDao;
	@Autowired
	private ShopExpressMoneyDao shopExpressMoneyDao;
	/*
	 * @Autowired private OrderBackDao orderBackDao;
	 */

	@Override
	public OrderOrderDO get(String id) {
		return orderOrderDao.get(id);
	}

	@Override
	public List<OrderOrderDO> list(Map<String, Object> map) {
		return orderOrderDao.list(map);
	}

	@Override
	public int count(Map<String, Object> map) {
		return orderOrderDao.count(map);
	}

	@Override
	public int save(OrderOrderDO orderOrder) {
		return orderOrderDao.save(orderOrder);
	}

	@Override
	public int update(OrderOrderDO orderOrder) {
		return orderOrderDao.update(orderOrder);
	}

	@Override
	public int remove(String id) {
		return orderOrderDao.remove(id);
	}

	@Override
	public int batchRemove(String[] ids) {
		return orderOrderDao.batchRemove(ids);
	}

	public static AtomicInteger race = new AtomicInteger(0);

	/* 购物车添加订单 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R addCartOrder(Map<String, Object> paramMap) {
		List<String> cartList = (List<String>) paramMap.get("cartList"); // 商品集合
		String userId = paramMap.get("userId").toString(); // 用户id
		int postType = Integer.valueOf(paramMap.get("postType").toString()); // 配送方式：0：自提，1：快递
		int payType = Integer.valueOf(paramMap.get("payType").toString()); // 0：微信支付，1：支付宝支付,
																			// 2余额支付
		String buyerMsg = paramMap.get("buyerMsg").toString(); // 留言
		String couponId = paramMap.get("couponId").toString(); // 优惠券id
		// 邮费
		BigDecimal postFee = new BigDecimal(paramMap.get("postFee").toString());
		/*try {
			postFee = getPostFees(paramMap, cartList);
		} catch (Exception e) {
			return R.error(e.toString());
		}*/
		// BigDecimal postFee = new
		// BigDecimal(paramMap.get("postFee").toString()); //邮费
		MemberUserDO user = memberUserDao.get(userId);
		int level = user.getLevel(); // 会员等级 0：省代，1：市代，2：县代，3：医生，4：普通用户
		Date date = new Date();

		// 订单表
		OrderOrderDO order = new OrderOrderDO();
		String order_sn = String.valueOf(Id.next()); // 订单号
		order.setOrderSn(order_sn);
		order.setId(UuidUtil.get32UUID());
		order.setCreateAt(date);
		order.setUpdateAt(date);
		order.setUserId(userId);
		order.setBuyerMsg(buyerMsg);
		order.setBuyerNick(user.getName());
		order.setDelFlag(0);
		order.setExport(0);
		order.setPostFee(postFee);
		order.setPostType(postType);
		order.setPaytype(payType);
		order.setSee(0);

		// 订单配送表
		String shopAddress = cmsContentDao.getByType("shop-address").getValue();
		OrderShippingDO shipping = new OrderShippingDO();
		shipping.setId(UuidUtil.get32UUID());
		shipping.setOrderId(order.getId());
		if (postType == 1) {
			String addressId = paramMap.get("addressId").toString(); // 收货地址
			MemberAddressDO memberAddress = memberAddressDao.get(addressId);
			shipping.setReceiverName(memberAddress.getFullName());
			shipping.setReceiverPhone(memberAddress.getPhone());
			shipping.setReceiverProvince(memberAddress.getProvince());
			shipping.setReceiverCity(memberAddress.getCity());
			shipping.setReceiverCounty(memberAddress.getCounty());
			shipping.setReceiverTown(memberAddress.getTown());
			shipping.setReceiverAddress(memberAddress.getAddress());
		}
		shipping.setCreateAt(date);
		shipping.setUpdateAt(date);
		shipping.setDelFlag(0);
		shipping.setShopAddress(shopAddress);
		orderShippingDao.save(shipping);

		// 订单详情表
		BigDecimal goodsPrice = new BigDecimal(0);
		/*
		 * BigDecimal rebateOnePrice = new BigDecimal(0); BigDecimal
		 * rebateTwoPrice = new BigDecimal(0);
		 */
		for (String cartId : cartList) {
			MemberCartDO cart = memberCartDao.get(cartId);
			String goodId = cart.getGoodsId(); // id
			int total = cart.getNum(); // 商品数量
			String productId = cart.getProductId(); // 商品规格id
			GoodsProductDO product = goodsProductDao.get(productId);
			GoodsGoodsDO goods = goodsGoodsDao.get(goodId);
			int stock = product.getStock(); // 库存
			// int isvip = goods.getIsvip();
			int isvip = 0;
			BigDecimal price = new BigDecimal(0); // 单价
			if (isvip == 0) {
				price = product.getPrice();
			} else {
				switch (level) {
				case 1:
					price = product.getPriceC();
					break;
				case 2:
					price = product.getPriceZ();
					break;
				case 3:
					price = product.getPriceG();
					break;
				default:
					price = product.getPrice();
				}
			}
			/*
			 * BigDecimal ro = product.getRebateOne(); BigDecimal rt =
			 * product.getRebateTwo();
			 */

			BigDecimal goodPrice = price.multiply(new BigDecimal(total));// 总价
			goodsPrice = goodsPrice.add(goodPrice);
			/*
			 * BigDecimal rebateOne = ro.multiply(new BigDecimal(total));
			 * //初级分销自反 rebateOnePrice = rebateOnePrice.add(rebateOne);
			 * BigDecimal rebateTwo = rt.multiply(new BigDecimal(total));
			 * //高级分销自反 rebateTwoPrice = rebateTwoPrice.add(rebateTwo);
			 */

			OrderDetailDO detailDO = new OrderDetailDO();
			detailDO.setId(UuidUtil.get32UUID());
			detailDO.setGoodsId(goodId);
			detailDO.setOrderId(order.getId());
			detailDO.setProductId(productId);
			detailDO.setPrice(price);
			detailDO.setAllPrice(goodPrice);
			detailDO.setComent(0);
			detailDO.setCreateAt(date);
			detailDO.setDelFlag(0);
			detailDO.setTotal(total);
			orderDetailDao.save(detailDO);
			// 修改商品库存、销量
			Map<String, Object> proMap = new HashMap<String, Object>();
			int newStock = stock - total;
			if (newStock < 0) {
				newStock = 0;
			}
			proMap.put("id", productId);
			proMap.put("newStock", newStock);
			proMap.put("oldStock", stock);
			int n = goodsProductDao.updateByOld(proMap);
			if (n == 0) {
				goodsProductDao.error(proMap);
			}
			// 销量添加
			int numSale = 0;
			if (goods.getNumSale() != null) {
				numSale = goods.getNumSale();
			}
			int num_sale = numSale + total;
			GoodsGoodsDO good = new GoodsGoodsDO();
			good.setId(goodId);
			good.setNumSale(num_sale);
			goodsGoodsDao.update(good);
			// 删除购物车
			memberCartDao.remove(cartId);
		}
		BigDecimal allPrice = new BigDecimal(0); // 订单总金额
		MemberCouponDO memberCouponDO = memberCouponDao.get(couponId);
		if (memberCouponDO != null) {
			BigDecimal couponMoney = memberCouponDO.getMoney(); // 优惠金额
			allPrice = goodsPrice.add(postFee).subtract(couponMoney); // 订单总金额
			// 修改用户优惠券
			MemberCouponDO couponDO = new MemberCouponDO();
			couponDO.setId(memberCouponDO.getId());
			couponDO.setStatus(1);
			couponDO.setOrderAt(date);
			couponDO.setUpdateAt(date);
			couponDO.setOrderId(order.getId());
			memberCouponDao.update(couponDO);
		} else {
			allPrice = goodsPrice.add(postFee);
		}

		// 一.开始分销
		startRebate(user, level, order, allPrice);

		// order_order补充
		order.setPayment(allPrice);
		order.setCouponId(couponId);
		order.setOrdertype(0);
		order.setStatus(1);
		order.setComent(0);
		orderOrderDao.save(order);
		Map<String, Object> mmm = new HashMap<>();
		mmm.put("orderId", order.getId());
		mmm.put("payType", order.getPaytype());
		return R.ok().put("data", mmm);
	}
	
	public BigDecimal getPostFees(Map<String, Object> paramMap, List<String> cartList) {
		BigDecimal postFee = new BigDecimal("0.00");
		for (String cartId : cartList) {
			MemberCartDO cart = memberCartDao.get(cartId);
			String goodsId = cart.getGoodsId();
			GoodsProductDO goodsProductDO = goodsProductDao.get(cart.getProductId());
			GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(goodsId);
			if (goodsGoodsDO.getPostSize() == 0) {
				// 通用邮费
				postFee = (postFee.add(goodsProductDO.getPostFee())).multiply(new BigDecimal(cart.getNum()));
			} else if (goodsGoodsDO.getPostSize() == 1) {
				// 模板
				// 收货地址
				MemberAddressDO memberAddress = memberAddressDao.get(paramMap.get("addressId").toString());
				Map<String, Object> shopExpressMoneyMap = new HashMap<>();
				shopExpressMoneyMap.put("name", memberAddress.getProvince());
				shopExpressMoneyMap.put("delFlag", "0");
				List<ShopExpressMoneyDO> shopExpressMoneyList = shopExpressMoneyDao.likeList(shopExpressMoneyMap);
				if (shopExpressMoneyList.size() <= 0) {
					System.out.println("地址信息有误");
					// return
					// R.error("抱歉,"+memberAddress.getProvince()+"地区不到!");
				} else {
					Double weight = goodsProductDO.getWeight();
					//总重量
					weight=weight*cart.getNum();
					//向上取整
					Double ceil = Math.ceil(weight);
					int intWeight = ceil.intValue();
					if (intWeight <= shopExpressMoneyList.get(0).getFirstWeight()) {
						postFee = postFee.add(shopExpressMoneyList.get(0).getFirstPrice());
					} else {
						// 邮费=首重价格+续重价格*续重kg //续重价格 //总重量-首重重量
						postFee = postFee.add(shopExpressMoneyList.get(0).getFirstPrice())
								.add(shopExpressMoneyList.get(0).getAddPrice().multiply(
										new BigDecimal(intWeight - shopExpressMoneyList.get(0).getFirstWeight())));
					}

				}
			}
		}
		return postFee;
	}

	public BigDecimal getPostFees(Map<String, Object> paramMap, String goodsId, String productId)  {
		BigDecimal postFee = new BigDecimal("0.00");
		GoodsProductDO goodsProductDO = goodsProductDao.get(productId);
		GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(goodsProductDO.getGoodsId());
		//数量
		Integer num = Integer.parseInt(paramMap.get("total").toString());
		if (goodsGoodsDO.getPostSize() == 0) {
			// 通用邮费
			postFee = (postFee.add(goodsProductDO.getPostFee())).multiply(new BigDecimal(num));
		} else if (goodsGoodsDO.getPostSize() == 1) {
			// 模板
			// 收货地址
			MemberAddressDO memberAddress = memberAddressDao.get(paramMap.get("addressId").toString());
			Map<String, Object> shopExpressMoneyMap = new HashMap<>();
			shopExpressMoneyMap.put("name", memberAddress.getProvince());
			shopExpressMoneyMap.put("delFlag", "0");
			List<ShopExpressMoneyDO> shopExpressMoneyList = shopExpressMoneyDao.likeList(shopExpressMoneyMap);
			if (shopExpressMoneyList.size() <= 0) {
				System.out.println("地址信息有误");
				// return R.error("抱歉,"+memberAddress.getProvince()+"地区不到!");
			} else {
				Double weight = goodsProductDO.getWeight();
				weight=weight*num;
				Double ceil = Math.ceil(weight);
				int intWeight = ceil.intValue();
				if (intWeight <= shopExpressMoneyList.get(0).getFirstWeight()) {
					postFee = postFee.add(shopExpressMoneyList.get(0).getFirstPrice());
				} else {
					// 邮费=首重价格+续重价格*续重kg //续重价格 //总重量-首重重量
					postFee = postFee.add(shopExpressMoneyList.get(0).getFirstPrice())
							.add(shopExpressMoneyList.get(0).getAddPrice().multiply(
									new BigDecimal(intWeight - shopExpressMoneyList.get(0).getFirstWeight())));
				}

			}
		}
		return postFee;
	}

	private void startRebate(MemberUserDO user, int level, OrderOrderDO order, BigDecimal allPrice) {
		if (level == 3) {
			// 1.医生消费只跟县级返佣,也就是间接推荐人
			// 1.1返现比例百分比
			CmsContentDO byType = cmsContentDao.getByType("money-buy-doctor");
			BigDecimal value = new BigDecimal(byType.getValue());
			saveOrderCom(order, allPrice, value, user);
		} else if (level == 4) {
			
			// 2.1.2 用户消费给自己返积分
			// 2.1.2.1 获取比例
			CmsContentDO byType = null;
			byType = cmsContentDao.getByType("money-buy-own");
			BigDecimal value = new BigDecimal(0.00);
			value = new BigDecimal(byType.getValue());
			MemberScoreDO memberScoreDO = new MemberScoreDO();
			memberScoreDO.setMoney(allPrice.multiply(value.divide(new BigDecimal(100))));
			// 2.1.2.2 往记录表插入数据
			saveMemberScore(user, order, user, memberScoreDO);
			// 2.用户消费
			String intorId = user.getIntroUser();
			// 有上级
			if (!"0".equals(intorId)) {
				// 父级==直推人
				MemberUserDO upUser = memberUserDao.get(intorId);
				// 2.1如果直推人是用户,如果第一次消费,给直推人大量积分,否则给直推人按比例积分,给医生和县级返佣金
				if (upUser.getLevel() == 4) {
					// 2.1.0 查看用户是否第一次消费
					int count = orderOrderDao.countByUserId(user.getId());
					// 2.1.1如果是,给直推人返大量积分
					//CmsContentDO byType = null;
					//BigDecimal value = new BigDecimal(0.00);
					//MemberScoreDO memberScoreDO = new MemberScoreDO();
					if (count <= 0) {
						// 2.1.1.0 获取第一次的积分个数
						byType = cmsContentDao.getByType("score-buy-one");
						value = new BigDecimal(byType.getValue());
						memberScoreDO.setMoney(value);
					} else {
						// 2.1.1.2如果不是第一次,给直推人返积分百分比
						byType = cmsContentDao.getByType("score-buy-up");
						value = new BigDecimal(byType.getValue());
						memberScoreDO.setMoney(allPrice.multiply(value.divide(new BigDecimal(100))));
					}
					// 2.1.1.3往积分表插入数据
					saveMemberScore(user, order, upUser, memberScoreDO);

					

				}
				// 2.2 不管直推人是医生还是用户,给医生和县级返佣金
				// 2.2.1 用户消费给医生也就是间接推荐人返佣金
				//CmsContentDO byType = null;
				//BigDecimal value = new BigDecimal(0.00);
				MemberUserDO memberUserDO = memberUserDao.get(user.getIndirectUser());
				if (memberUserDO != null) {
					// 2.2.2返现比例百分比
					byType = cmsContentDao.getByType("money-buy-one");
					value = new BigDecimal(byType.getValue());
					saveOrderCom(order, allPrice, value, user);
					// 2.2.4 用户消费给县级也就是间接推荐人的间接推荐人返佣金
					MemberUserDO up2User = memberUserDao.get(memberUserDO.getIndirectUser());
					if (up2User != null) {
						// 2.2.5返现比例百分比
						byType = cmsContentDao.getByType("money-buy-county");
						value = new BigDecimal(byType.getValue());
						// 2.2.6返佣表插入记录
						saveOrderCom(order, allPrice, value, memberUserDO);
					}
				}
				

			} /*else {
				// 没有上级,只给自己返积分
				CmsContentDO byType = cmsContentDao.getByType("money-buy-own");
				BigDecimal value = new BigDecimal(byType.getValue());
				MemberScoreDO memberScoreDO = new MemberScoreDO();
				memberScoreDO.setMoney(allPrice.multiply(value.divide(new BigDecimal(100))));
				// 2.1.2.2 往记录表插入数据
				saveMemberScore(user, order, user, memberScoreDO);
			}*/
		}
	}

	private void saveMemberScore(MemberUserDO user, OrderOrderDO order, MemberUserDO upUser,
			MemberScoreDO memberScoreDO) {
		memberScoreDO.setCreateAt(new Date());
		memberScoreDO.setDelFlag(0);
		memberScoreDO.setGId(order.getId());
		memberScoreDO.setId(UUIDUtils.getUUID());
		memberScoreDO.setMemberId(user.getId());
		if(user.getId().equals(upUser.getId())){
			memberScoreDO.setType(3);
		}else{
			memberScoreDO.setType(0);
		}
		
		memberScoreDO.setUserId(upUser.getId());
		memberScoreDao.save(memberScoreDO);
	}

	private void saveOrderCom(OrderOrderDO order, BigDecimal allPrice, BigDecimal value, MemberUserDO up2User) {
		OrderComDO comDO = new OrderComDO();
		comDO.setComPrice(allPrice.multiply(value.divide(new BigDecimal(100))));
		comDO.setCreateAt(new Date());
		comDO.setDelFlag(0);
		comDO.setOrderId(order.getId());
		comDO.setStatus(0);
		comDO.setUserId(up2User.getIndirectUser());
		comDO.setId(UUIDUtils.getUUID());
		orderComDao.save(comDO);
	}

	/* 商品详情添加订单，仅限于 普通、秒杀、9.9专区商品、拼团、会员专区 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R addGoodsOrder(Map<String, Object> paramMap) {
		Integer type = Integer.valueOf(paramMap.get("type").toString()); // type
																			// 0：普通商品，1:9.9商品，2：秒杀商品，4：拼团商品，5：会员专区商品6:积分商品
		String productId = paramMap.get("productId").toString(); // 规格id
		int postType = Integer.valueOf(paramMap.get("postType").toString()); // 配送方式：0：自提，1：快递
		int payType = Integer.valueOf(paramMap.get("payType").toString()); // 0：微信支付，1：支付宝支付,
																			// 2积分支付
		String id = paramMap.get("id").toString(); // type为0时传商品id，type为1时传秒杀id，type为2时传9.9专区id,
													// type为4时传拼团id，type为5时传会员专区id type为5时传商品id
		Integer total = Integer.valueOf(paramMap.get("total").toString()); // 商品数量
		String userId = paramMap.get("userId").toString(); // 用户id
		String buyerMsg = paramMap.get("buyerMsg").toString(); // 留言
		String couponId = paramMap.get("couponId").toString(); // 优惠券id
		//邮费
		BigDecimal postFee = new BigDecimal(paramMap.get("postFee").toString());
		/*try {
			GoodsProductDO goodsProductDO = goodsProductDao.get(productId);
			postFee = getPostFees(paramMap, goodsProductDO.getGoodsId(), productId);
		} catch (Exception e) {
			return R.error(e.toString());
		}*/
		// BigDecimal postFee = new
		// BigDecimal(paramMap.get("postFee").toString()); //邮费
		MemberUserDO user = memberUserDao.get(userId);
		int level = user.getLevel();
		String goodsId = "";
		Date date = new Date();

		// 订单表
		OrderOrderDO order = new OrderOrderDO();
		String order_sn = String.valueOf(Id.next()); // 订单号
		order.setOrderSn(order_sn);
		order.setId(UuidUtil.get32UUID());
		order.setCreateAt(date);
		order.setUpdateAt(date);
		order.setUserId(userId);
		order.setBuyerMsg(buyerMsg);
		order.setBuyerNick(user.getName());
		order.setDelFlag(0);
		order.setExport(0);
		order.setPostFee(postFee);
		order.setPostType(postType);
		order.setPaytype(payType);
		order.setSee(0);

		// 订单配送表
		String shopAddress = cmsContentDao.getByType("shop-address").getValue();
		OrderShippingDO shipping = new OrderShippingDO();
		shipping.setId(UuidUtil.get32UUID());
		shipping.setOrderId(order.getId());
		if (postType == 1) {
			String addressId = paramMap.get("addressId").toString(); // 收货地址
			MemberAddressDO memberAddress = memberAddressDao.get(addressId);
			shipping.setReceiverName(memberAddress.getFullName());
			shipping.setReceiverPhone(memberAddress.getPhone());
			shipping.setReceiverProvince(memberAddress.getProvince());
			shipping.setReceiverCity(memberAddress.getCity());
			shipping.setReceiverCounty(memberAddress.getCounty());
			shipping.setReceiverTown(memberAddress.getTown());
			shipping.setReceiverAddress(memberAddress.getAddress());
		}
		shipping.setCreateAt(date);
		shipping.setUpdateAt(date);
		shipping.setDelFlag(0);
		shipping.setShopAddress(shopAddress);
		orderShippingDao.save(shipping);

		// 订单详情表
		BigDecimal price = new BigDecimal(0);
		BigDecimal goodsPrice = new BigDecimal(0);
		/*
		 * BigDecimal rebateOnePrice = new BigDecimal(0); BigDecimal
		 * rebateTwoPrice = new BigDecimal(0);
		 */
		// 判库存，填价格，定返佣，改销量
		GoodsProductDO product = goodsProductDao.get(productId);
		int stock = product.getStock(); // 规格库存
		if (type == 2) { // 秒杀商品
			GoodsSpikeDO spikeDO = goodsSpikeDao.get(id);
			goodsId = spikeDO.getGoodsId();
			GoodsGoodsDO goodsDO = goodsGoodsDao.get(goodsId);
			int isvip = goodsDO.getIsvip();
			if (isvip == 0) {
				price = spikeDO.getPrice();
			} else {
				switch (level) {
				case 1:
					price = spikeDO.getPriceC();
					break;
				case 2:
					price = spikeDO.getPriceZ();
					break;
				case 3:
					price = spikeDO.getPriceG();
					break;
				default:
					price = spikeDO.getPrice();
				}
			}
			goodsPrice = price.multiply(new BigDecimal(total));
			// 总价
			/*
			 * rebateOnePrice = spikeDO.getRebateOne().multiply(new
			 * BigDecimal(total)); //一级返佣 rebateTwoPrice =
			 * spikeDO.getRebateTwo().multiply(new BigDecimal(total)); //二级返佣
			 */ int spikeNumSale = spikeDO.getNumSale() + total; // 新秒杀销量
			int spikeStoke = spikeDO.getStock(); // 旧库存
			int newSpikeStock = spikeStoke - total; // 新库存
			Map<String, Object> spikeMap = new HashMap<String, Object>();
			if (newSpikeStock < 0) {
				newSpikeStock = 0;
			}
			spikeMap.put("id", id);
			spikeMap.put("newStock", newSpikeStock);
			spikeMap.put("oldStock", spikeStoke);
			spikeMap.put("spikeNumSale", spikeNumSale);
			int n = goodsSpikeDao.updateByOld(spikeMap);
			if (n == 0) {
				goodsProductDao.error(spikeMap);
			}
		} else if (type == 4) { // 拼团商品
			GoodsTeamDO teamDO = goodsTeamDao.get(id);
			goodsId = teamDO.getGoodsId();
			GoodsGoodsDO goodsDO = goodsGoodsDao.get(goodsId);
			int isvip = goodsDO.getIsvip();
			if (isvip == 0) {
				price = teamDO.getPrice();
			} else {
				switch (level) {
				case 1:
					price = teamDO.getPriceC();
					break;
				case 2:
					price = teamDO.getPriceZ();
					break;
				case 3:
					price = teamDO.getPriceG();
					break;
				default:
					price = teamDO.getPrice();
				}
			}
			goodsPrice = price.multiply(new BigDecimal(total));
			// 总价
			/*
			 * rebateOnePrice = teamDO.getRebateOne().multiply(new
			 * BigDecimal(total)); //一级返佣 rebateTwoPrice =
			 * teamDO.getRebateTwo().multiply(new BigDecimal(total)); //二级返佣
			 */ int teamNumSale = teamDO.getNumSale() + total; // 新秒杀销量
			int teamStoke = teamDO.getStock(); // 旧库存
			int newTeamStock = teamStoke - total; // 新库存
			Map<String, Object> teamMap = new HashMap<String, Object>();
			if (newTeamStock < 0) {
				newTeamStock = 0;
			}
			teamMap.put("id", id);
			teamMap.put("newStock", newTeamStock);
			teamMap.put("oldStock", teamStoke);
			teamMap.put("teamNumSale", teamNumSale);
			int n = goodsTeamDao.updateByOld(teamMap);
			if (n == 0) {
				goodsProductDao.error(teamMap);
			}
			order.setDelFlag(1);
			// 添加拼团订单表
			if (!paramMap.containsKey("teamId") || StringUtils.isBlank(paramMap.get("teamId").toString())) {
				OrderTeamDO orderTeamDO = new OrderTeamDO();
				orderTeamDO.setId(UuidUtil.get32UUID());
				orderTeamDO.setGoodsTeamId(id);
				orderTeamDO.setTime(teamDO.getTime());
				orderTeamDO.setNumber(teamDO.getNumber());
				orderTeamDO.setCreateAt(date);
				orderTeamDO.setUpdateAt(DateUtils.addHourOfDate(date, teamDO.getTime()));
				orderTeamDO.setDelFlag(0);
				orderTeamDao.save(orderTeamDO);
				OrderTeamUserDO orderTeamUserDO = new OrderTeamUserDO();
				orderTeamUserDO.setId(UuidUtil.get32UUID());
				orderTeamUserDO.setOrderId(order.getId());
				orderTeamUserDO.setIsMain(1);
				orderTeamUserDO.setCreateAt(date);
				orderTeamUserDO.setUpdateAt(date);
				orderTeamUserDO.setDelFlag(0);
				orderTeamUserDO.setOrderTeamId(orderTeamDO.getId());
				orderTeamUserDao.save(orderTeamUserDO);
			} else {
				OrderTeamUserDO orderTeamUserDO = new OrderTeamUserDO();
				orderTeamUserDO.setId(UuidUtil.get32UUID());
				orderTeamUserDO.setOrderId(order.getId());
				orderTeamUserDO.setIsMain(0);
				orderTeamUserDO.setCreateAt(date);
				orderTeamUserDO.setUpdateAt(date);
				orderTeamUserDO.setDelFlag(0);
				orderTeamUserDO.setOrderTeamId(paramMap.get("teamId").toString());
				orderTeamUserDao.save(orderTeamUserDO);
			}
		} else if (type == 5) { // 会员专区商品
			GoodsUpgradeDO upgradeDO = goodsUpgradeDao.get(id);
			goodsId = upgradeDO.getGoodsId();
			price = upgradeDO.getPrice();
			goodsPrice = price.multiply(new BigDecimal(total));// 总价
			/*
			 * rebateOnePrice = upgradeDO.getRebateOne().multiply(new
			 * BigDecimal(total)); //一级返佣 rebateTwoPrice =
			 * upgradeDO.getRebateTwo().multiply(new BigDecimal(total)); //二级返佣
			 */
			int upgradeNumSale = upgradeDO.getNumSale() + total; // 新秒杀销量
			int upgradeStoke = upgradeDO.getStock(); // 旧库存
			int newUpgradeStock = upgradeStoke - total; // 新库存
			Map<String, Object> upgradeMap = new HashMap<String, Object>();
			if (newUpgradeStock < 0) {
				newUpgradeStock = 0;
			}
			upgradeMap.put("id", id);
			upgradeMap.put("newStock", newUpgradeStock);
			upgradeMap.put("oldStock", upgradeStoke);
			upgradeMap.put("upgradeNumSale", upgradeNumSale);
			int n = goodsUpgradeDao.updateByOld(upgradeMap);
			if (n == 0) {
				goodsProductDao.error(upgradeMap);
			}
		} else if (type == 0) { // 普通商品
			goodsId = id;
			GoodsGoodsDO goodsDO = goodsGoodsDao.get(goodsId);
			int isvip = goodsDO.getIsvip();
			if (isvip == 0) {
				price = product.getPrice();
			} else {
				switch (level) {
				case 1:
					price = product.getPriceC();
					break;
				case 2:
					price = product.getPriceZ();
					break;
				case 3:
					price = product.getPriceG();
					break;
				default:
					price = product.getPrice();
				}
			}
			goodsPrice = price.multiply(new BigDecimal(total));
			// 总价
			/*
			 * rebateOnePrice = product.getRebateOne().multiply(new
			 * BigDecimal(total)); //一级返佣 rebateTwoPrice =
			 * product.getRebateTwo().multiply(new BigDecimal(total)); //二级返佣
			 */ }else if (type == 6) { // 积分商品
					goodsId = id;
					GoodsGoodsDO goodsDO = goodsGoodsDao.get(goodsId);
					price = product.getPrice().multiply(new BigDecimal(total));
					
					goodsPrice = postFee;
					// 总价
					/*
					 * rebateOnePrice = product.getRebateOne().multiply(new
					 * BigDecimal(total)); //一级返佣 rebateTwoPrice =
					 * product.getRebateTwo().multiply(new BigDecimal(total)); //二级返佣
					 */ }

		OrderDetailDO detailDO = new OrderDetailDO();
		detailDO.setId(UuidUtil.get32UUID());
		detailDO.setGoodsId(goodsId);
		detailDO.setOrderId(order.getId());
		detailDO.setProductId(productId);
		detailDO.setPrice(price);
		detailDO.setAllPrice(goodsPrice);
		detailDO.setComent(0);
		detailDO.setCreateAt(date);
		detailDO.setDelFlag(0);
		detailDO.setTotal(total);
		if (type == 5) { // 会员专区商品
			GoodsUpgradeDO upgradeDO = goodsUpgradeDao.get(id);
			detailDO.setUpLevel(upgradeDO.getLevel());
		}
		orderDetailDao.save(detailDO);
		// 修改商品库存、销量
		Map<String, Object> proMap = new HashMap<String, Object>();
		int newStock = stock - total;
		if (newStock < 0) {
			newStock = 0;
		}
		proMap.put("id", productId);
		proMap.put("newStock", newStock);
		proMap.put("oldStock", stock);
		int n = goodsProductDao.updateByOld(proMap);
		if (n == 0) {
			goodsProductDao.error(proMap);
		}
		// 销量添加
		GoodsGoodsDO goods = goodsGoodsDao.get(goodsId);
		int numSale = 0;
		if (goods.getNumSale() != null) {
			numSale = goods.getNumSale();
		}
		int num_sale = numSale + total;
		GoodsGoodsDO good = new GoodsGoodsDO();
		good.setId(goodsId);
		good.setNumSale(num_sale);
		goodsGoodsDao.update(good);

		BigDecimal allPrice = new BigDecimal(0);
		MemberCouponDO memberCouponDO = memberCouponDao.get(couponId);
		if (memberCouponDO != null) {
			BigDecimal couponMoney = memberCouponDO.getMoney(); // 优惠金额
			allPrice = goodsPrice.add(postFee).subtract(couponMoney); // 订单总金额
			// 修改用户优惠券
			MemberCouponDO couponDO = new MemberCouponDO();
			couponDO.setId(memberCouponDO.getId());
			couponDO.setStatus(1);
			couponDO.setOrderAt(date);
			couponDO.setUpdateAt(date);
			couponDO.setOrderId(order.getId());
			memberCouponDao.update(couponDO);
		} else {
			allPrice = goodsPrice.add(postFee); // 订单总金额
		}

		// 开始分销
		if(type!=6){
			startRebate(user, level, order, allPrice);
		}else{
			//添加消费积分记录(默认已消费)
			MemberScoreDO memberScoreDO = new MemberScoreDO();
			memberScoreDO.setCreateAt(new Date());
			memberScoreDO.setDelFlag(0);
			memberScoreDO.setgId(order.getId());
			memberScoreDO.setId(UUIDUtils.getUUID());
			memberScoreDO.setMemberId(user.getId());
			memberScoreDO.setMoney(price);
			if(goodsPrice.compareTo(new BigDecimal("0.00"))==0){
				memberScoreDO.setStatus(0);
			}else{
				memberScoreDO.setStatus(1);
			}
			memberScoreDO.setStatus(1);
			memberScoreDO.setType(5);
			memberScoreDO.setUserId(user.getId());
			memberScoreDao.save(memberScoreDO);
		}
		
		/*
		 * String intorId = user.getIntroUser(); int prevLevel = level;
		 * //前一个人的等级（参与分销的） for (int i=1; i<3; i++) { if (intorId == null ||
		 * "".equals(intorId)) { break; } MemberUserDO productUser =
		 * memberUserDao.get(intorId); int intorLevel = productUser.getLevel();
		 * //父级等级 if (productUser == null) { break; } int disbled =
		 * productUser.getDisabled(); if (disbled == 1) { //如果账号被冻结 i--; intorId
		 * = productUser.getIntroUser(); continue; }
		 * 
		 * if (prevLevel<4) { if (intorLevel > 3) { //父级能吃返佣,10% OrderComDO
		 * comDO = new OrderComDO(); comDO.setId(UuidUtil.get32UUID());
		 * comDO.setCreateAt(date); comDO.setDelFlag(0);
		 * comDO.setOrderId(order.getId());
		 * comDO.setComPrice(allPrice.multiply(new BigDecimal(10).divide(new
		 * BigDecimal(100)))); comDO.setStatus(0); comDO.setUpdateAt(date);
		 * comDO.setUserId(intorId); orderComDao.save(comDO); prevLevel =
		 * intorLevel; } } else if (prevLevel==4 && intorLevel==5) { //反 5%
		 * OrderComDO comDO = new OrderComDO();
		 * comDO.setId(UuidUtil.get32UUID()); comDO.setCreateAt(date);
		 * comDO.setDelFlag(0); comDO.setOrderId(order.getId());
		 * comDO.setComPrice(allPrice.multiply(new BigDecimal(5).divide(new
		 * BigDecimal(100)))); comDO.setStatus(0); comDO.setUpdateAt(date);
		 * comDO.setUserId(intorId); orderComDao.save(comDO); prevLevel =
		 * intorLevel; } intorId = productUser.getIntroUser(); }
		 */
		// order_order补充
		if(type==6){
			order.setPayment(goodsPrice);
		}else{
			order.setPayment(allPrice);
		}
		if(order.getPayment().compareTo(new BigDecimal("0.00"))==0){
			order.setStatus(3);
		}else{
			order.setStatus(1);
		}
		order.setCouponId(couponId);
		order.setOrdertype(type);
		
		order.setComent(0);
		orderOrderDao.save(order);
		Map<String, Object> mmm = new HashMap<>();
		mmm.put("orderId", order.getId());
		mmm.put("payType", order.getPaytype());
		return R.ok().put("data", mmm);
	}

	/* 购买砍价商品，创建订单--弃用 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R addBargainGoodsOrder(Map<String, Object> paramMap) {
		String productId = paramMap.get("productId").toString(); // 规格id
		String bargainId = paramMap.get("bargainId").toString(); // 砍价id
		Integer total = Integer.valueOf(paramMap.get("total").toString()); // 商品数量，固定为
																			// 1
		String userId = paramMap.get("userId").toString(); // 用户id
		String buyerMsg = paramMap.get("buyerMsg").toString(); // 留言
		String couponId = paramMap.get("couponId").toString(); // 优惠券id
		// 邮费
		BigDecimal postFee;
		try {
			GoodsProductDO goodsProductDO = goodsProductDao.get(productId);
			postFee = getPostFees(paramMap, goodsProductDO.getGoodsId(), productId);
		} catch (Exception e) {
			return R.error(e.toString());
		}
		//BigDecimal postFee = new BigDecimal(paramMap.get("postFee").toString()); // 邮费
		String addressId = paramMap.get("addressId").toString(); // 收货地址
		MemberUserDO user = memberUserDao.get(userId);
		int level = user.getLevel();
		Date date = new Date();
		GoodsBargainDO goodsBargainDO = goodsBargainDao.get(bargainId);
		String goodsId = goodsBargainDO.getGoodsId();

		// 订单表
		OrderOrderDO order = new OrderOrderDO();
		String order_sn = String.valueOf(Id.next()); // 订单号
		order.setOrderSn(order_sn);
		order.setId(UuidUtil.get32UUID());
		order.setCreateAt(date);
		order.setUpdateAt(date);
		order.setUserId(userId);
		order.setBuyerMsg(buyerMsg);
		order.setBuyerNick(user.getName());
		order.setDelFlag(0);
		order.setExport(0);
		order.setPostFee(postFee);

		// 砍价订单详情
		OrderBargainDO bargainDO = new OrderBargainDO();
		bargainDO.setId(UuidUtil.get32UUID());
		bargainDO.setOrderId(order.getId());
		bargainDO.setDelFlag(0);
		bargainDO.setPrice(goodsBargainDO.getPrice());
		bargainDO.setMinPrice(goodsBargainDO.getMinPrice());
		bargainDO.setMaxPrice(goodsBargainDO.getMaxPrice());
		bargainDO.setRebateOne(goodsBargainDO.getRebateOne());
		bargainDO.setRebateTwo(goodsBargainDO.getRebateTwo());
		bargainDO.setStartAt(date);
		Date endAt = DateUtils.addHourOfDate(date, goodsBargainDO.getTime());
		bargainDO.setEndAt(endAt);
		orderBargainDao.save(bargainDO);

		// 订单配送表
		MemberAddressDO memberAddress = memberAddressDao.get(addressId);
		OrderShippingDO shipping = new OrderShippingDO();
		shipping.setId(UuidUtil.get32UUID());
		shipping.setOrderId(order.getId());
		shipping.setReceiverName(memberAddress.getFullName());
		shipping.setReceiverPhone(memberAddress.getPhone());
		shipping.setReceiverProvince(memberAddress.getProvince());
		shipping.setReceiverCity(memberAddress.getCity());
		shipping.setReceiverCounty(memberAddress.getCounty());
		shipping.setReceiverTown(memberAddress.getTown());
		shipping.setReceiverAddress(memberAddress.getAddress());
		shipping.setCreateAt(date);
		shipping.setUpdateAt(date);
		shipping.setDelFlag(0);
		orderShippingDao.save(shipping);

		// 订单详情表
		BigDecimal price = new BigDecimal(0);
		BigDecimal goodsPrice = new BigDecimal(0);
		BigDecimal rebateOnePrice = new BigDecimal(0);
		BigDecimal rebateTwoPrice = new BigDecimal(0);
		// 判库存，填价格，定返佣，改销量
		GoodsProductDO product = goodsProductDao.get(productId);
		int stock = product.getStock(); // 规格库存
		price = goodsBargainDO.getPrice();
		goodsPrice = price.multiply(new BigDecimal(total));// 总价
		rebateOnePrice = goodsBargainDO.getRebateOne().multiply(new BigDecimal(total)); // 一级返佣
		rebateTwoPrice = goodsBargainDO.getRebateTwo().multiply(new BigDecimal(total)); // 二级返佣
		int bargainNumSale = goodsBargainDO.getNumSale() + total; // 新秒杀销量
		int bargainStock = goodsBargainDO.getStock(); // 旧秒杀库存
		int newBarStock = bargainStock - total; // 新秒杀库存
		Map<String, Object> spikeMap = new HashMap<String, Object>();
		if (newBarStock < 0) {
			newBarStock = 0;
		}
		spikeMap.put("id", bargainId);
		spikeMap.put("newStock", newBarStock);
		spikeMap.put("oldStock", bargainStock);
		spikeMap.put("numSale", bargainNumSale);
		int n = goodsBargainDao.updateByOld(spikeMap);
		if (n == 0) {
			goodsProductDao.error(spikeMap);
		}

		OrderDetailDO detailDO = new OrderDetailDO();
		detailDO.setId(UuidUtil.get32UUID());
		detailDO.setGoodsId(goodsId);
		detailDO.setOrderId(order.getId());
		detailDO.setProductId(productId);
		detailDO.setPrice(price);
		detailDO.setAllPrice(goodsPrice);
		detailDO.setComent(0);
		detailDO.setCreateAt(date);
		detailDO.setDelFlag(0);
		detailDO.setTotal(total);
		orderDetailDao.save(detailDO);
		// 修改商品库存、销量
		Map<String, Object> proMap = new HashMap<String, Object>();
		int newStock = stock - total;
		if (newStock < 0) {
			newStock = 0;
		}
		proMap.put("id", productId);
		proMap.put("newStock", newStock);
		proMap.put("oldStock", stock);
		int m = goodsProductDao.updateByOld(proMap);
		if (m == 0) {
			goodsProductDao.error(proMap);
		}
		// 销量添加
		GoodsGoodsDO goods = goodsGoodsDao.get(goodsId);
		int numSale = 0;
		if (goods.getNumSale() != null) {
			numSale = goods.getNumSale();
		}
		int num_sale = numSale + total;
		GoodsGoodsDO good = new GoodsGoodsDO();
		good.setId(goodsId);
		good.setNumSale(num_sale);
		goodsGoodsDao.update(good);

		BigDecimal allPrice = new BigDecimal(0);
		MemberCouponDO memberCouponDO = memberCouponDao.get(couponId);
		if (memberCouponDO != null) {
			BigDecimal couponMoney = memberCouponDO.getMoney(); // 优惠金额
			allPrice = goodsPrice.add(postFee).subtract(couponMoney); // 订单总金额
			// 修改用户优惠券
			MemberCouponDO couponDO = new MemberCouponDO();
			couponDO.setId(memberCouponDO.getId());
			couponDO.setStatus(1);
			couponDO.setOrderAt(date);
			couponDO.setUpdateAt(date);
			couponDO.setOrderId(order.getId());
			memberCouponDao.update(couponDO);
		} else {
			allPrice = goodsPrice.add(postFee); // 订单总金额
		}

		// 开始分销
		startRebate(user, level, order, allPrice);
		/*
		 * String intorId = user.getIntroUser(); for (int i=1; i<3; i++) { if
		 * (intorId == null || "".equals(intorId)) { break; } MemberUserDO
		 * productUser = memberUserDao.get(intorId); if (productUser == null) {
		 * break; } int disbled = productUser.getDisabled(); if (disbled == 1) {
		 * //如果账号被冻结,找下一个 i--; intorId = productUser.getIntroUser(); continue; }
		 * 
		 * BigDecimal money = new BigDecimal(0); if (i == 1) { money =
		 * rebateOnePrice; } else if (i == 2) { money = rebateTwoPrice; }
		 * OrderComDO comDO = new OrderComDO();
		 * comDO.setId(UuidUtil.get32UUID()); comDO.setCreateAt(date);
		 * comDO.setDelFlag(0); comDO.setOrderId(order.getId());
		 * comDO.setComPrice(money); comDO.setStatus(0);
		 * comDO.setUpdateAt(date); comDO.setUserId(intorId);
		 * orderComDao.save(comDO); intorId = productUser.getIntroUser(); }
		 */
		// order_order补充
		order.setPayment(allPrice);
		order.setCouponId(couponId);
		order.setOrdertype(3);
		order.setStatus(0);
		order.setComent(0);
		orderOrderDao.save(order);
		return R.ok();
	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public PageInfo<Map<String, Object>> getOrderListByStatus(Map<String, Object> paramMap) {
		// 更新拼团订单状态
		List<Map<String, Object>> updateList = orderOrderDao.getTeamOrderStatus(paramMap);
		for (Map<String, Object> updateMap : updateList) {
			int paytype = Integer.valueOf(updateMap.get("paytype").toString());
			String orderId = updateMap.get("orderId").toString();
			if (paytype == 2) { // 余额支付
				// 复原余额
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("gId", orderId);
				map.put("type", "0");
				MemberPriceDO memberPriceDO = memberPriceDao.list(map).get(0);
				memberPriceDO.setDelFlag(1);
				memberPriceDao.update(memberPriceDO);
			} else if (paytype == 0) { // 微信支付
				R r = weChatPayService.refund(updateMap);
			}
			OrderOrderDO orderOrderDO = new OrderOrderDO();
			orderOrderDO.setId(updateMap.get("orderId").toString());
			orderOrderDO.setStatus(10);
			orderOrderDao.update(orderOrderDO);
		}

		PageHelperUtils.page(paramMap);
		String type = paramMap.get("type").toString(); // 类型
		String userId = paramMap.get("userId").toString(); // 会员id
		String[] status = new String[10];
		if (type.equals("1")) { // 待支付
			status[0] = "1";
		} else if (type.equals("2")) { // 待发货
			status[0] = "3";
		} else if (type.equals("7")) { // 拼团中
			status[0] = "2";
		} else if (type.equals("3")) { // 待收货
			status[0] = "4";
			status[1] = "11";
		} else if (type.equals("4")) { // 待评价
			status[0] = "7";
		} else if (type.equals("5")) { // 问题订单
			status[0] = "5";
			status[1] = "6";
		} else if (type.equals("0")) { // 全部
			// status[0] = "0";
			status[0] = "1";
			status[1] = "2";
			status[2] = "3";
			status[3] = "4";
			status[4] = "7";
			status[5] = "5";
			status[6] = "8";
			status[7] = "10";
			status[8] = "6";
			/*
			 * status[9] = "9"; status[10] = "10";
			 */
		}
		paramMap.put("status", status);
		List<Map<String, Object>> list = orderOrderDao.getOrderListByStatus(paramMap);
		for (Map<String, Object> map : list) {
			String orderId = map.get("id").toString();
			List<Map<String, Object>> detailList = orderDetailDao.getByOrderId(orderId);
			map.put("detailList", detailList);
			if(paramMap.get("type").toString().equals("5")){
				OrderBackDO orderBackDO = orderBackDao.getByOrderId(orderId);
				map.put("orderBackDO", orderBackDO);
			}
		}
		PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
		return pageInfo;
	}

	/* 会员取消订单、收货 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int setStatusOrder(Map<String, Object> paramMap) {
		String userId = paramMap.get("userId").toString();
		String orderId = paramMap.get("orderId").toString();
		String type = paramMap.get("type").toString();
		Date date = new Date();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		map.put("id", orderId);
		OrderOrderDO orderDO = orderOrderDao.get(orderId);
		MemberUserDO userDO = memberUserDao.get(userId);
		if ("8".equals(type)) { // 取消订单
			if (orderDO.getStatus() != 1) {
				return 1;
			}
			OrderOrderDO order = new OrderOrderDO();
			order.setId(orderId);
			order.setStatus(8);
			order.setUpdateAt(date);
			orderOrderDao.update(order);
			// 删除返利的佣金
			orderComDao.removeCom(orderId);
			// 删除返的(扣除)积分
			memberScoreDao.removeScore(orderId);
		} else if ("7".equals(type)) { // 收货
			if (orderDO.getStatus() != 4 && orderDO.getStatus() != 11) {
				return 1;
			}
			OrderOrderDO order = new OrderOrderDO();
			order.setId(orderId);
			order.setStatus(7);
			order.setUpdateAt(date);
			order.setReceivingAt(date);
			order.setEndAt(date);
			orderOrderDao.update(order);
			if(orderDO.getPaytype()!=2){
				// 修改佣金和积分到账
				updateCmsAndScore(date, order);
			}
			
			/*
			 * map.clear();
			 * 
			 * map.put("orderId", orderId); map.put("delFlag", "0");
			 * List<OrderComDO> comDOList = orderComDao.list(map);
			 * if(comDOList.size()>0){ for (OrderComDO orderComDO : comDOList) {
			 * MemberPriceDO priceDO = new MemberPriceDO();
			 * priceDO.setId(UuidUtil.get32UUID()); priceDO.setGId(orderId);
			 * priceDO.setType(3); priceDO.setDelFlag(0);
			 * priceDO.setCreateAt(date); priceDO.setUpdateAt(date);
			 * priceDO.setUserId(orderComDO.getUserId());
			 * priceDO.setPrice(orderComDO.getComPrice());
			 * memberPriceDao.save(priceDO); orderComDO.setStatus(2);
			 * orderComDO.setUpdateAt(date); orderComDao.update(orderComDO); } }
			 * //修改积分状态 List<MemberScoreDO> scoreList =
			 * memberScoreDao.getByOrderId(orderId); if(scoreList.size()>0){ for
			 * (MemberScoreDO memberScoreDO : scoreList) {
			 * memberScoreDO.setStatus(1); memberScoreDO.setUpdateAt(new
			 * Date()); memberScoreDao.update(memberScoreDO); } }
			 */
			// 插入积分记录
			/*
			 * OrderOrderDO orderOrderDO = orderOrderDao.get(orderId);
			 * BigDecimal value = new
			 * BigDecimal(cmsContentDao.getByType("score-buy").getValue());
			 * BigDecimal score =
			 * value.multiply(orderOrderDO.getPayment()).divide(new
			 * BigDecimal(100)); MemberScoreDO scoreDO = new MemberScoreDO();
			 * scoreDO.setId(UuidUtil.get32UUID()); scoreDO.setType(0);
			 * scoreDO.setUserId(userId); scoreDO.setDelFlag(0);
			 * scoreDO.setCreateAt(date); scoreDO.setUpdateAt(date);
			 * scoreDO.setGId(order.getId()); scoreDO.setMoney(score);
			 * memberScoreDao.save(scoreDO); //查询是否升级 int level =
			 * userDO.getLevel(); int newLevel = 0; if (level > 0) { newLevel =
			 * 1; } int orderType = orderDO.getOrdertype(); if (orderType == 5)
			 * { OrderDetailDO detailDO = orderDetailDao.list(map).get(0); int
			 * upLevel = detailDO.getUpLevel(); if (upLevel > level) { //人物升级
			 * newLevel = upLevel; } } //查询升级数据 map.clear(); SimpleDateFormat
			 * format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			 * map.put("userId", userId); Date Eight =
			 * DateUtils.subDayOfDate(DateUtils.getDayBegin(),180); //180天前 Date
			 * nine = DateUtils.subDayOfDate(DateUtils.getDayBegin(), 90);
			 * //90天前 map.put("sTime", format.format(Eight)); BigDecimal
			 * eightNum = memberUserDao.getShoppingNum(map); //180天的消费值
			 * map.put("sTime", format.format(nine)); BigDecimal nineNum =
			 * memberUserDao.getShoppingNum(map); //90天的消费值 map.clear();
			 * map.put("userId", userId); map.put("level", new int[]{1, 2, 3});
			 * int hyNum = memberUserDao.getZtChildrenNUm(map); //直推会员人数
			 * map.put("level",new int[]{4}); int cfNum =
			 * memberUserDao.getZtChildrenNUm(map); //直推初级分销人数 BigDecimal
			 * payment = orderDO.getPayment(); //单笔消费金额 //判断是否满足初级会员
			 * MemberUpgradeDO upgradeDO1 =
			 * memberUpgradeService.getByLevel("1"); if
			 * (eightNum.compareTo(upgradeDO1.getAllPrice()) != -1) { //180天金额满足
			 * newLevel = 1; } if (payment.compareTo(upgradeDO1.getOnePrice())
			 * != -1) { //单笔金额满足 newLevel = 1; } //判断是否满足中级会员 MemberUpgradeDO
			 * upgradeDO2 = memberUpgradeService.getByLevel("2"); if
			 * (eightNum.compareTo(upgradeDO2.getAllPrice()) != -1) { //180天金额满足
			 * newLevel = 2; } if (payment.compareTo(upgradeDO2.getOnePrice())
			 * != -1) { //单笔金额满足 newLevel = 2; } //判断是否满足高级会员 MemberUpgradeDO
			 * upgradeDO3 = memberUpgradeService.getByLevel("3"); if
			 * (eightNum.compareTo(upgradeDO3.getAllPrice()) != -1) { //180天金额满足
			 * newLevel = 3; } if (payment.compareTo(upgradeDO3.getOnePrice())
			 * != -1) { //单笔金额满足 newLevel = 3; } //判断是否满足初级分销 MemberUpgradeDO
			 * upgradeDO4 = memberUpgradeService.getByLevel("4"); if
			 * (nineNum.compareTo(upgradeDO4.getAllPrice()) != -1) { //金额满足 if
			 * (hyNum >= 1) { //满足推广要求 newLevel = 4; } } if (hyNum >= 2) {
			 * //满足单独推广要求 newLevel = 4; } //判断是否满足高级分销 MemberUpgradeDO
			 * upgradeDO5 = memberUpgradeService.getByLevel("5"); if
			 * (nineNum.compareTo(upgradeDO5.getAllPrice()) != -1) { //金额满足 if
			 * (cfNum >= 1 && hyNum >= 1) { //满足推广要求 newLevel = 5; } } if (cfNum
			 * >= 3 && hyNum >= 2) { //满足单独推广要求 newLevel = 5; } //等级变化 if (level
			 * > 3 && newLevel< level) { //分销不降级 newLevel = level; } if
			 * (newLevel != level) { MemberUserDO memberUserDO = new
			 * MemberUserDO(); memberUserDO.setId(userId);
			 * memberUserDO.setLevel(newLevel);
			 * memberUserDao.update(memberUserDO); //添加等级变动记录
			 * MemberLevelChangeDO changeDO = new MemberLevelChangeDO();
			 * changeDO.setId(UuidUtil.get32UUID());
			 * changeDO.setOldLevel(level); changeDO.setNewLevel(newLevel);
			 * changeDO.setCreateAt(date); changeDO.setUpdateAt(date);
			 * changeDO.setDelFlag(0); changeDO.setUserId(userId);
			 * changeDO.setComent("180天的消费值："+eightNum+"，90天的消费值："+nineNum+
			 * "，单笔金额："+payment+"，直推会员人数："+hyNum+"，直推初级分销人数："+cfNum);
			 * memberLevelChangeDao.save(changeDO); }
			 */
		}
		return 0;
	}

	/* 后台自提成功,弃用 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R ziTi(OrderOrderDO order) {
		/*
		 * String orderId = order.getId(); Date date = new Date();
		 * order.setStatus(7); order.setUpdateAt(date);
		 * order.setReceivingAt(date); order.setEndAt(date);
		 * orderOrderDao.update(order); //插入我的余额表 Map<String,Object> map = new
		 * HashMap<String,Object>(); map.put("orderId", orderId);
		 * List<OrderComDO> comDOList = orderComDao.list(map); for (OrderComDO
		 * orderComDO : comDOList) { MemberPriceDO priceDO = new
		 * MemberPriceDO(); priceDO.setId(UuidUtil.get32UUID());
		 * priceDO.setGId(orderId); priceDO.setType(3); priceDO.setDelFlag(0);
		 * priceDO.setCreateAt(date); priceDO.setUpdateAt(date);
		 * priceDO.setUserId(orderComDO.getUserId());
		 * priceDO.setPrice(orderComDO.getComPrice());
		 * memberPriceDao.save(priceDO); } //插入积分记录 OrderOrderDO orderOrderDO =
		 * orderOrderDao.get(orderId); BigDecimal value = new
		 * BigDecimal(cmsContentDao.getByType("score-buy").get(0).getValue());
		 * BigDecimal score =
		 * value.multiply(orderOrderDO.getPayment()).divide(new
		 * BigDecimal(100)); MemberScoreDO scoreDO = new MemberScoreDO();
		 * scoreDO.setId(UuidUtil.get32UUID()); scoreDO.setType(0);
		 * scoreDO.setUserId(orderOrderDO.getUserId()); scoreDO.setDelFlag(0);
		 * scoreDO.setCreateAt(date); scoreDO.setUpdateAt(date);
		 * scoreDO.setGId(order.getId()); scoreDO.setMoney(score);
		 * memberScoreDao.save(scoreDO);
		 */
		return R.ok();
	}

	/* 去评论 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int setComent(Map<String, Object> paramMap) {
		String userId = paramMap.get("userId").toString();
		String orderId = paramMap.get("orderId").toString();
		Date date = new Date();
		List<Map<String, Object>> comentList = (List<Map<String, Object>>) (paramMap.get("comentList"));
		for (Map<String, Object> comentMap : comentList) {
			int start = new Integer(comentMap.get("start").toString());
			String content = comentMap.get("content").toString();
			String detailId = comentMap.get("detailId").toString();
			String imgurls = StringUtils.getString(comentMap.get("imgurls"));
			if (StringUtils.isBlank(content)) {
				return 1;
			}
			// 评论表
			OrderComentDO comentDO = new OrderComentDO();
			comentDO.setId(UuidUtil.get32UUID());
			comentDO.setContent(content);
			comentDO.setDetailId(detailId);
			comentDO.setStar(start);
			comentDO.setDisply(0);
			comentDO.setCreateAt(date);
			comentDO.setUserId(userId);
			comentDO.setImgurls(imgurls);
			orderComentDao.save(comentDO);
			// 修改detail表
			OrderDetailDO detailDO = new OrderDetailDO();
			detailDO.setId(detailId);
			detailDO.setComent(1);
			orderDetailDao.update(detailDO);
			// 修改商品评论量
			OrderDetailDO orderDetailDO = orderDetailDao.get(detailId);
			String goodsId = orderDetailDO.getGoodsId();
			GoodsGoodsDO goodsGoodsDO = goodsGoodsDao.get(goodsId);
			int newNum = goodsGoodsDO.getNumComment() + 1;
			GoodsGoodsDO goodsDO = new GoodsGoodsDO();
			goodsDO.setId(goodsId);
			goodsDO.setNumComment(newNum);
			goodsGoodsDao.update(goodsDO);
		}
		OrderOrderDO orderOrderDO = new OrderOrderDO();
		orderOrderDO.setId(orderId);
		orderOrderDO.setComent(1);
		orderOrderDao.update(orderOrderDO);
		return 0;
	}

	@Override
	public Map<String, Object> getOrderById(Map<String, Object> paramMap) {
		Map<String, Object> orderMap = orderOrderDao.getOrderById(paramMap);
		List<OrderDetailDO> detailList = orderDetailDao.list(paramMap);
		List<Map<String, Object>> goodsList = new ArrayList<Map<String, Object>>();
		BigDecimal goodsAllPrice = new BigDecimal(0);
		int allTotal = 0;
		for (OrderDetailDO detailDO : detailList) {
			Map<String, Object> map = new HashMap<String, Object>();
			String goodsId = detailDO.getGoodsId();
			String productId = detailDO.getProductId();
			BigDecimal goodsPrice = detailDO.getPrice();
			BigDecimal total = new BigDecimal(detailDO.getTotal());
			allTotal = allTotal + detailDO.getTotal();
			goodsAllPrice = goodsAllPrice.add(goodsPrice.multiply(total));
			GoodsProductDO productDO = goodsProductDao.get(productId);
			GoodsGoodsDO goodsDO = goodsGoodsDao.get(goodsId);
			map.put("total", total);
			map.put("imgurl", goodsDO.getImgurl());
			map.put("goodsName", goodsDO.getName());
			map.put("goodsPrice", goodsPrice);
			map.put("spec", productDO.getSpec());
			map.put("goodsId", goodsDO.getId());
			map.put("detailId", detailDO.getId());
			goodsList.add(map);
		}
		orderMap.put("goodsList", goodsList);
		orderMap.put("goodsAllPrice", goodsAllPrice);
		orderMap.put("allTotal", allTotal);
		// 查询优惠券金额
		String coupon_id = StringUtils.getString(orderMap.get("coupon_id"));
		if (coupon_id.equals("")) {
			orderMap.put("couponPrice", "0");
		} else {
			MemberCouponDO couponDO = memberCouponDao.get(coupon_id);
			orderMap.put("couponPrice", couponDO.getMoney());
		}
		return orderMap;
	}

	/* 拼团订单详情 */
	@Override
	public Map<String, Object> getPOrderById(Map<String, Object> paramMap) {
		Map<String, Object> orderMap = orderOrderDao.getOrderById(paramMap);
		List<OrderDetailDO> detailList = orderDetailDao.list(paramMap);
		List<Map<String, Object>> goodsList = new ArrayList<Map<String, Object>>();
		BigDecimal goodsAllPrice = new BigDecimal(0);
		int allTotal = 0;
		for (OrderDetailDO detailDO : detailList) {
			Map<String, Object> map = new HashMap<String, Object>();
			String goodsId = detailDO.getGoodsId();
			String productId = detailDO.getProductId();
			BigDecimal goodsPrice = detailDO.getPrice();
			BigDecimal total = new BigDecimal(detailDO.getTotal());
			allTotal = allTotal + detailDO.getTotal();
			goodsAllPrice = goodsAllPrice.add(goodsPrice.multiply(total));
			GoodsProductDO productDO = goodsProductDao.get(productId);
			GoodsGoodsDO goodsDO = goodsGoodsDao.get(goodsId);
			map.put("total", total);
			map.put("imgurl", goodsDO.getImgurl());
			map.put("goodsName", goodsDO.getName());
			map.put("goodsPrice", goodsPrice);
			map.put("spec", productDO.getSpec());
			map.put("goodsId", goodsDO.getId());
			map.put("detailId", detailDO.getId());
			goodsList.add(map);
		}
		orderMap.put("goodsList", goodsList);
		orderMap.put("goodsAllPrice", goodsAllPrice);
		orderMap.put("allTotal", allTotal);
		// 得到拼团信息
		Map<String, Object> teamMap = orderTeamUserDao.getTeamByOrderId(paramMap);
		orderMap.put("needNUm", teamMap.get("number"));
		orderMap.put("endTeamTime", teamMap.get("update_at"));
		// 查询优惠券金额
		String coupon_id = StringUtils.getString(orderMap.get("coupon_id"));
		if (coupon_id.equals("")) {
			orderMap.put("couponPrice", "0");
		} else {
			MemberCouponDO couponDO = memberCouponDao.get(coupon_id);
			orderMap.put("couponPrice", couponDO.getMoney());
		}
		// 查询拼团人
		List<Map<String, Object>> userList = orderTeamUserDao.getUserByOrder(paramMap);
		orderMap.put("userList", userList);
		return orderMap;
	}

	/* 砍价订单详情 */
	@Override
	public Map<String, Object> getKOrderById(Map<String, Object> paramMap) {
		Map<String, Object> orderMap = orderOrderDao.getOrderById(paramMap);
		List<OrderDetailDO> detailList = orderDetailDao.list(paramMap);
		List<Map<String, Object>> goodsList = new ArrayList<Map<String, Object>>();
		BigDecimal goodsAllPrice = new BigDecimal(0);
		for (OrderDetailDO detailDO : detailList) {
			Map<String, Object> map = new HashMap<String, Object>();
			String goodsId = detailDO.getGoodsId();
			String productId = detailDO.getProductId();
			BigDecimal goodsPrice = detailDO.getPrice();
			BigDecimal total = new BigDecimal(detailDO.getTotal());
			goodsAllPrice = goodsAllPrice.add(goodsPrice.multiply(total));
			GoodsProductDO productDO = goodsProductDao.get(productId);
			GoodsGoodsDO goodsDO = goodsGoodsDao.get(goodsId);
			map.put("total", total);
			map.put("imgurl", goodsDO.getImgurl());
			map.put("goodsName", goodsDO.getName());
			map.put("goodsPrice", goodsPrice);
			map.put("spec", "");
			map.put("goodsId", goodsDO.getId());
			map.put("detailId", detailDO.getId());
			goodsList.add(map);
		}
		orderMap.put("goodsList", goodsList);
		orderMap.put("goodsAllPrice", goodsAllPrice);
		// 查询优惠券金额
		String coupon_id = StringUtils.getString(orderMap.get("coupon_id"));
		if (coupon_id.equals("")) {
			orderMap.put("couponPrice", "0");
		} else {
			MemberCouponDO couponDO = memberCouponDao.get(coupon_id);
			orderMap.put("couponPrice", couponDO.getMoney());
		}
		// 查询帮忙砍价人
		List<Map<String, Object>> userList = orderBargainUserDao.getUserByOrder(paramMap);
		orderMap.put("userList", userList);
		return orderMap;
	}

	@Override
	public List<Map<String, Object>> getOrderList(Map<String, Object> map) {
		return orderOrderDao.getOrderList(map);
	}

	@Override
	public int getOrderListCount(Map<String, Object> map) {
		return orderOrderDao.getOrderListCount(map);
	}

	/**
	 * 添加物流
	 * 
	 * @param order
	 * @return
	 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int addShipping(OrderOrderDO order) {
		Date date = new Date();
		ShopExpressCodeDO codeDO = shopExpressCodeDao.queryByCode(order.getShippingName());
		ShopExpressMessageDO messageDO = shopExpressMessageDao.queryByOrderId(order.getId());
		if (messageDO == null && codeDO != null) {
			order.setStatus(4);
			order.setUpdateAt(date);
			order.setConsignAt(date);
			orderOrderDao.update(order);

			messageDO = new ShopExpressMessageDO();
			messageDO.setId(UuidUtil.get32UUID());
			messageDO.setStatus(0);
			messageDO.setName(codeDO.getName());
			// messageDO.setCode(order.getShippingCode());
			messageDO.setCode(codeDO.getCode());
			messageDO.setExpressId(order.getShippingCode());
			messageDO.setUserId(order.getUserId());
			messageDO.setDelFlag(Constant.DEFAULT_DEL_FLAG);
			messageDO.setOpAt(new Date());
			messageDO.setOrderId(order.getId());
			shopExpressMessageDao.save(messageDO);

			// 推送
			/*
			 * OrderOrderDO orderOrderDO = orderOrderDao.get(order.getId());
			 * String userId = orderOrderDO.getUserId(); List<String> newList =
			 * new ArrayList<String>(); newList.add(userId); String content =
			 * "您的订单已发货，订单号为："+orderOrderDO.getOrderSn();
			 * jPushService.checkPush(newList, content, 0, "0");
			 */
			// 发信息
			/*
			 * Map<String,Object> shippingMap
			 * =orderOrderDao.getOrderById(order.getId()); String mobile =
			 * shippingMap.get("receiver_phone").toString(); String name =
			 * shippingMap.get("name").toString(); String shippingCode =
			 * orderOrderDO.getShippingCode(); String code = " "+name+
			 * "已发货，详情请查询 "+codeDO.getName()+"："+shippingCode+""; try {
			 * JuSms.sendFSms(mobile, code); } catch (IOException e) {
			 * e.printStackTrace(); return 1; }
			 */
			return 1;
		}
		return 0;
	}

	/**
	 * 修改物流
	 * 
	 * @param order
	 * @return
	 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int editShipping(OrderOrderDO order) {
		Date date = new Date();
		String orderId = order.getId();
		ShopExpressCodeDO codeDO = shopExpressCodeDao.queryByCode(order.getShippingName());
		ShopExpressMessageDO messageDO = shopExpressMessageDao.queryByOrderId(orderId);
		if (messageDO != null && codeDO != null) {
			order.setStatus(4);
			order.setUpdateAt(date);
			order.setConsignAt(date);
			orderOrderDao.update(order);

			// 先删除旧信息
			shopExpressMessageDao.remove(messageDO.getId());
			shopExpressDetailsDao.removeByOrderId(orderId);

			ShopExpressMessageDO newMessageDO = new ShopExpressMessageDO();
			newMessageDO.setId(UuidUtil.get32UUID());
			newMessageDO.setStatus(0);
			newMessageDO.setName(codeDO.getName());
			// newMessageDO.setCode(order.getShippingCode());
			newMessageDO.setCode(codeDO.getCode());
			newMessageDO.setExpressId(order.getShippingCode());
			newMessageDO.setUserId(order.getUserId());
			newMessageDO.setDelFlag(Constant.DEFAULT_DEL_FLAG);
			newMessageDO.setOpAt(new Date());
			newMessageDO.setOrderId(order.getId());
			shopExpressMessageDao.save(newMessageDO);

			// 推送
			/*
			 * OrderOrderDO orderOrderDO = orderOrderDao.get(order.getId());
			 * String userId = orderOrderDO.getUserId(); List<String> newList =
			 * new ArrayList<String>(); newList.add(userId); String content =
			 * "您的订单已发货，订单号为："+orderOrderDO.getOrderSn();
			 * jPushService.checkPush(newList, content, 0, "0");
			 */
			return 1;
		}
		return 0;
	}

	@Override
	public Map<String, Object> getHOrderById(String id) {
		return orderOrderDao.getHOrderById(id);
	}

	@Override
	public List<Map<String, Object>> statisticsList(Map<String, Object> map) {
		return orderOrderDao.statisticsList(map);
	}

	@Override
	public int statisticsCount(Map<String, Object> map) {
		return orderOrderDao.statisticsCount(map);
	}

	@Override
	public List<Map<String, Object>> getDetailGoods(Map<String, Object> map) {
		return orderOrderDao.getDetailGoods(map);
	}

	@Override
	public int getDetailGoodsCount(Map<String, Object> map) {
		return orderOrderDao.getDetailGoodsCount(map);
	}

	@Override
	public List<Map<String, Object>> getKUsers(Map<String, Object> map) {
		return orderOrderDao.getKUsers(map);
	}

	@Override
	public int getKUsersCount(Map<String, Object> map) {
		return orderOrderDao.getKUsersCount(map);
	}

	/* 导出excel。改变订单导出状态 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public void exportExcel(Map<String, Object> map, List<Map<String, Object>> userList, ServletOutputStream out,
			HttpServletRequest request) {
		// 导出excel
		if (OrderExcelUtils.exportUserExcel(userList, out) == 1) {
			// 改变订单导出状态
			int number = orderOrderDao.updateExportByMap(map);
			// 添加导出记录
			Long customId = getUserId();
			String userName = userDao.get(customId).getUsername(); // 管理员账号
			OrderExcelRecodeDO recode = new OrderExcelRecodeDO();
			recode.setId(UuidUtil.get32UUID());
			recode.setCreateAt(new Date());
			recode.setUserPhone(userName);
			recode.setNumber(number);
			recode.setIp(IPUtils.getIp(request));
			orderExcelRecodeDao.save(recode);
		}
	}

	/*
	 * 导入excel表格
	 */
	@Override
	public void importExcel(MultipartFile file, String excelFileName) {
		// 1.创建输入流
		try {
			// FileInputStream inputStream = new FileInputStream(file);
			// boolean is03Excel = excelFileName.matches("^.+\\.(?i)(xls)$");
			// 1.读取工作簿
			boolean is03Excel = excelFileName.matches("^.+\\.(?i)(xls)$");
			Workbook workbook = is03Excel ? new HSSFWorkbook(file.getInputStream())
					: new XSSFWorkbook(file.getInputStream());
			// Workbook workbook = new HSSFWorkbook(file.getInputStream());
			// 2.读取工作表
			Sheet sheet = workbook.getSheetAt(0);
			// 3.读取行
			// 判断行数大于一,是因为数据从第二行开始插入
			int num = sheet.getPhysicalNumberOfRows();
			if (sheet.getPhysicalNumberOfRows() > 1) {
				// 跳过前一行
				for (int k = 1; k < sheet.getPhysicalNumberOfRows(); k++) {
					// 读取单元格
					Row row0 = sheet.getRow(k);
					// 订单id
					Cell cell0 = row0.getCell(0);
					cell0.setCellType(Cell.CELL_TYPE_STRING);
					String order_sn = cell0.getStringCellValue().replace("\t", "").trim();
					// 物流名
					String shipping_name = "";
					Cell cell9 = row0.getCell(1);
					if (cell9 == null) {
						shipping_name = "";
					} else {
						cell9.setCellType(Cell.CELL_TYPE_STRING);
						shipping_name = cell9.getStringCellValue().replace("\t", "").trim();
					}
					// 物流单号
					String shipping_code = "";
					Cell cell10 = row0.getCell(2);
					if (cell10 == null) {
						shipping_code = "";
					} else {
						cell10.setCellType(Cell.CELL_TYPE_STRING);
						shipping_code = cell10.getStringCellValue().replace("\t", "").trim();
					}
					if (!("".equals(order_sn.trim()) || "".equals(shipping_name.trim())
							|| "".equals(shipping_code.trim()))) {
						OrderOrderDO ceOrder = orderOrderDao.getByOrder(order_sn);
						int status = ceOrder.getStatus();
						String id = ceOrder.getId();
						if (status == 6) {
							OrderOrderDO order = new OrderOrderDO();
							order.setId(id);
							order.setShippingName(shipping_name.trim());
							order.setShippingCode(shipping_code.trim());
							order.setUserId(ceOrder.getUserId());
							addShipping(order);
						}
					}
				}
			}
			workbook.close();
			// inputStream.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/* 后台退货列表 */
	@Override
	public List<Map<String, Object>> getBackOrderList(Map<String, Object> map) {
		return orderOrderDao.getBackOrderList(map);
	}

	@Override
	public int getBackOrderListCount(Map<String, Object> map) {
		return orderOrderDao.getBackOrderListCount(map);
	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int backOrder(OrderOrderDO order) {
		String orderId = order.getId();
		int status = order.getStatus();
		order.setUpdateAt(new Date());
		OrderOrderDO orderOrderDO = orderOrderDao.get(orderId);
		if (5 != orderOrderDO.getStatus()) {
			return 0;
		}
		if (status == 6) { // 确认
			orderOrderDao.update(order);
			orderComDao.updateByOrderId(orderId);
			// 销量和库存恢复原状
			Map<String, Object> mm = new HashMap<>();
			mm.put("orderId", orderId);
			List<OrderDetailDO> detailList = orderDetailDao.list(mm);
			for (OrderDetailDO detail : detailList) {
				String goodsId = detail.getGoodsId();
				String productId = detail.getProductId();
				int total = detail.getTotal();
				// 库存添加
				GoodsProductDO pr = goodsProductDao.get(productId);
				GoodsProductDO pro = new GoodsProductDO();
				int newStock = pr.getStock() + total;
				pro.setId(productId);
				pro.setStock(newStock);
				goodsProductDao.update(pro);
				// 销量减去
				GoodsGoodsDO goods = goodsGoodsDao.get(goodsId);
				int num_sale = goods.getNumSale() - total;
				GoodsGoodsDO good = new GoodsGoodsDO();
				good.setId(goodsId);
				good.setNumSale(num_sale);
				goodsGoodsDao.update(good);
			}
		} else if (status == 4) { // 驳回
			int postType = orderOrderDO.getPostType();
			if (postType == 0) {
				order.setStatus(11);
			} else if (postType == 1) {
				order.setStatus(4);
			}

			orderOrderDao.update(order);
			orderBackDao.removeByOrder(orderId);
		}
		return 1;
	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public int backGood(Map<String, Object> paramMap) {
		Date date = new Date();
		String id = paramMap.get("id").toString();
		String expressName = StringUtils.getString(paramMap.get("expressName"));
		String expressCode = StringUtils.getString(paramMap.get("expressCode"));
		String reason = paramMap.get("reason").toString();

		// 修改订单表
		OrderOrderDO order = new OrderOrderDO();
		order.setId(id);
		order.setStatus(5);
		order.setReturnAt(date);
		order.setUpdateAt(date);
		orderOrderDao.update(order);
		// 添加退货记录
		OrderBackDO orderBackDO = new OrderBackDO();
		orderBackDO.setId(UuidUtil.get32UUID());
		orderBackDO.setOrderId(id);
		orderBackDO.setExpressName(expressName);
		orderBackDO.setExpressCode(expressCode);
		orderBackDO.setReason(reason);
		orderBackDO.setCreateAt(date);
		orderBackDO.setUpdateAt(date);
		orderBackDO.setDelFlag(0);
		orderBackDao.save(orderBackDO);

		// 推送
		/*
		 * List<String> sList = new ArrayList<String>(); OrderOrderDO
		 * orderOrderDO = orderOrderDao.get(id); Object oneId =
		 * orderOrderDO.getUserH(); Object twoId = orderOrderDO.getUserL(); if
		 * (oneId != null && !("".equals(oneId))) { sList.add(oneId.toString());
		 * if (twoId != null && !("".equals(twoId))) {
		 * sList.add(twoId.toString()); } String content =
		 * "您提交的订单已经申请退货，订单号为："+orderOrderDO.getOrderSn();
		 * jPushService.checkPush(sList, content, 0, "0"); }
		 */
		return 1;
	}

	@Override
	public OrderOrderDO getByOrder(String orderSn) {
		return orderOrderDao.getByOrder(orderSn);
	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R removeOrder(Map<String, Object> map) {
		String userId = map.get("userId").toString();
		List<String> orderIdList = (List<String>) (map.get("orderIdList"));
		MemberUserDO user = memberUserDao.get(userId);
		if (user == null) {
			return R.error("会员信息错误");
		}
		for (String orderId : orderIdList) {
			OrderOrderDO orderOrderDO = orderOrderDao.get(orderId);
			int status = orderOrderDO.getStatus();
			if (status == 7 || status == 6 || status == 8 || status == 9 || status == 10) {
				OrderOrderDO order = new OrderOrderDO();
				order.setId(orderId);
				order.setSee(1);
				orderOrderDao.update(order);
			}
		}
		return R.ok();
	}

	/* 支付修改订单状态 */
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R pricePay(Map<String, Object> params) {
		String orderId = params.get("orderId").toString();
		String userId = params.get("userId").toString();
		int payType = Integer.valueOf(params.get("payType").toString()); // 0：微信支付，1：支付宝支付,
																			// 2余额支付
		Date date = new Date();
		OrderOrderDO orderOrderDO = orderOrderDao.get(orderId);
		int orderType = orderOrderDO.getOrdertype(); // 订单类型
														// 0：普通订单,1：秒杀订单，2：9.9订单，3：砍价订单，4：拼团订单,5：会员升级订单
		// 修改订单状态
		OrderOrderDO order = new OrderOrderDO();
		order.setId(orderId);
		int post_type = orderOrderDO.getPostType();
		if (orderType == 4) { // 拼团订单
			order.setStatus(2);
			order.setDelFlag(0);
		} else {
			if (post_type == 0) { // 自提
				order.setStatus(11);
			} else if (post_type == 1) { // 快递
				order.setStatus(3);
			}
		}
		order.setPaytype(payType);
		order.setPayAt(new Date());
		orderOrderDao.update(order);
		if (payType == 2) { // 如果是余额支付
			// 插入余额记录
			MemberPriceDO priceDO = new MemberPriceDO();
			priceDO.setId(UuidUtil.get32UUID());
			priceDO.setDelFlag(0);
			priceDO.setGId(orderId);
			priceDO.setType(0);
			priceDO.setCreateAt(date);
			priceDO.setUpdateAt(date);
			priceDO.setPrice(orderOrderDO.getPayment());
			priceDO.setUserId(userId);
			memberPriceDao.save(priceDO);
		}
		// 查询拼团订单是否完成
		if (orderType == 4) {
			Map<String, Object> teamMap = orderTeamUserDao.getPayTeamOrder(orderId);
			int haveNumber = Integer.valueOf(teamMap.get("haveNumber").toString());
			int allNumber = Integer.valueOf(teamMap.get("allNumber").toString());
			if (haveNumber >= allNumber) { // 拼团完成
				orderTeamUserDao.successTeam(orderId);
			}
		}
		return R.ok();
	}

	@Override
	public Map<String, Object> getTeamOrder(Map<String, Object> map) {
		String userId = map.get("userId").toString();
		String orderId = map.get("orderId").toString();
		MemberUserDO memberUserDO = memberUserDao.get(userId);
		int level = 0;
		if (memberUserDO != null) {
			map.put("level", memberUserDO.getLevel());
			level = memberUserDO.getLevel();
		} else {
			map.put("level", 0);
			level = 0;
		}
		Map<String, Object> orderMap = orderOrderDao.getTeamOrder(map);
		if (orderMap == null) {
			return R.error(1, "该商品暂时不能拼团");
		}
		List<Map<String, Object>> userList = orderTeamUserDao.getUserByOrder(map);
		orderMap.put("userList", userList);
		return R.ok().put("data", orderMap);

	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public void receivingOrderJob() {
		System.out.println("11111111111111111111111111111111111111111");
		int value = orderSetDao.list(new HashMap<String, Object>()).get(0).getValue();
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date aa = DateUtils.subDayOfDate(date, value);
		String day = format.format(aa);// 几天前的时间
		List<OrderOrderDO> orderList = orderOrderDao.receivingOrderJob(day);
		for (OrderOrderDO order : orderList) {
			if(order.getStatus()==4){
				order.setStatus(7);
				order.setEndAt(date);
				order.setUpdateAt(date);
				orderOrderDao.update(order);
				// 订单完成后返佣到账
				updateCmsAndScore(date, order);
			}else if(order.getStatus()==1){
				order.setStatus(8);
				order.setUpdateAt(date);
				orderOrderDao.update(order);
				// 删除返利的佣金
				orderComDao.removeCom(order.getId());
				// 删除返的(扣除)积分
				memberScoreDao.removeScore(order.getId());
			}
			
		}
	}

	private void updateCmsAndScore(Date date, OrderOrderDO order) {
		Map<String, Object> map = new HashMap<>();
		map.put("orderId", order.getId());
		map.put("delFlag", "0");
		List<OrderComDO> comDOList = orderComDao.list(map);
		if (comDOList.size() > 0) {
			for (OrderComDO orderComDO : comDOList) {
				MemberPriceDO priceDO = new MemberPriceDO();
				priceDO.setId(UuidUtil.get32UUID());
				priceDO.setGId(order.getId());
				priceDO.setType(3);
				priceDO.setDelFlag(0);
				priceDO.setCreateAt(date);
				priceDO.setUpdateAt(date);
				priceDO.setUserId(orderComDO.getUserId());
				priceDO.setPrice(orderComDO.getComPrice());
				memberPriceDao.save(priceDO);
				orderComDO.setStatus(2);
				orderComDO.setUpdateAt(date);
				orderComDao.update(orderComDO);
			}
		}
		// 修改返佣积分状态
		List<MemberScoreDO> scoreList = memberScoreDao.getByOrderId(order.getId());
		if (scoreList.size() > 0) {
			for (MemberScoreDO memberScoreDO : scoreList) {
				memberScoreDO.setStatus(1);
				memberScoreDO.setUpdateAt(date);
				memberScoreDao.update(memberScoreDO);
			}
		}
	}

}
